<template>
  <div class="brand-layout">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>品牌管理</h2>
      <div class="header-actions">
        <button class="btn btn-primary" @click="showAddModal = true">
          <span class="icon">+</span>
          新增品牌
        </button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-group">
          <label>品牌名称</label>
          <input v-model="searchForm.brandName" type="text" placeholder="请输入品牌名称" class="form-control" />
        </div>
        <div class="form-group">
          <label>品牌编码</label>
          <input v-model="searchForm.brandCode" type="text" placeholder="请输入品牌编码" class="form-control" />
        </div>
        <div class="form-group">
          <label>状态</label>
          <select v-model="searchForm.status" class="form-control">
            <option value="">全部状态</option>
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </div>
        <div class="form-group">
          <label>创建时间</label>
          <div class="date-range">
            <input v-model="searchForm.startTime" type="datetime-local" class="form-control" />
            <span class="date-separator">至</span>
            <input v-model="searchForm.endTime" type="datetime-local" class="form-control" />
          </div>
        </div>
        <div class="form-actions">
          <button class="btn btn-primary" @click="handleSearch"><span class="icon">🔍</span>搜索</button>
          <button class="btn btn-secondary" @click="handleReset"><span class="icon">🔄</span>重置</button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>品牌ID</th>
              <th>品牌名称</th>
              <th>品牌编码</th>
              <th>品牌描述</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>更新时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in tableData" :key="item.id">
              <td>{{ item.id }}</td>
              <td class="brand-name">{{ item.brandName }}</td>
              <td>{{ item.brandCode }}</td>
              <td class="brand-desc">{{ item.description || '-' }}</td>
              <td>
                <span :class="['status-badge', item.status === 1 ? 'active' : 'inactive']">
                  {{ item.status === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td>{{ formatDate(item.createdAt) }}</td>
              <td>{{ formatDate(item.updatedAt) }}</td>
              <td class="actions">
                <button class="btn btn-sm btn-info" @click="handleEdit(item)"><span class="icon">✏️</span>编辑</button>
                <button class="btn btn-sm btn-danger" @click="handleDelete(item)"><span class="icon">🗑️</span>删除</button>
              </td>
            </tr>
          </tbody>
        </table>

        <div v-if="tableData.length === 0" class="empty-state">
          <div class="empty-icon">🏷️</div>
          <p>暂无品牌数据</p>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <div class="pagination-info">共 {{ total }} 条记录，当前第 {{ currentPage }} 页</div>
      <div class="pagination-controls">
        <button 
          class="btn btn-sm" 
          :disabled="currentPage <= 1" 
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        <button 
          class="btn btn-sm" 
          :disabled="currentPage >= totalPages" 
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑品牌弹窗 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑品牌' : '新增品牌' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>品牌名称 <span class="required">*</span></label>
            <input v-model="brandForm.brandName" type="text" placeholder="请输入品牌名称" class="form-control" />
          </div>
          <div class="form-group">
            <label>品牌编码 <span class="required">*</span></label>
            <input v-model="brandForm.brandCode" type="text" placeholder="请输入品牌编码" class="form-control" />
          </div>
          <div class="form-group">
            <label>品牌描述</label>
            <textarea v-model="brandForm.description" placeholder="请输入品牌描述" class="form-control" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model="brandForm.status" class="form-control">
              <option value="1">启用</option>
              <option value="0">禁用</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="closeModal">取消</button>
          <button class="btn btn-confirm" @click="handleSubmit" :disabled="submitting">
            {{ submitting ? '提交中...' : '确定' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="showDeleteModal = false">
      <div class="modal delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="showDeleteModal = false">×</button>
        </div>
        <div class="modal-body">
          <p>确定要删除品牌 "{{ deleteItem?.brandName }}" 吗？此操作不可恢复。</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="showDeleteModal = false">取消</button>
          <button class="btn btn-danger" @click="confirmDelete" :disabled="deleting">
            {{ deleting ? '删除中...' : '确定删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getBrandPage, createBrand, updateBrand, deleteBrand } from '@/api/commodity'

// 响应式数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const submitting = ref(false)
const deleting = ref(false)
const deleteItem = ref(null)

// 搜索表单
const searchForm = reactive({
  brandName: '',
  brandCode: '',
  status: '',
  startTime: '',
  endTime: ''
})

// 品牌表单
const brandForm = reactive({
  id: null,
  brandName: '',
  brandCode: '',
  description: '',
  status: 1
})

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 获取品牌列表
const loadBrandList = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getBrandPage(params)
    if (response.code === 0) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      console.error('获取品牌列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadBrandList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  loadBrandList()
}

// 分页
const handlePageChange = (page) => {
  currentPage.value = page
  loadBrandList()
}

// 编辑品牌
const handleEdit = (item) => {
  Object.assign(brandForm, {
    id: item.id,
    brandName: item.brandName,
    brandCode: item.brandCode,
    description: item.description || '',
    status: item.status
  })
  showEditModal.value = true
}

// 删除品牌
const handleDelete = (item) => {
  deleteItem.value = item
  showDeleteModal.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!deleteItem.value) return
  
  deleting.value = true
  try {
    const response = await deleteBrand(deleteItem.value.id)
    if (response.code === 0) {
      showDeleteModal.value = false
      deleteItem.value = null
      loadBrandList()
    } else {
      alert(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除品牌失败:', error)
    alert('删除失败')
  } finally {
    deleting.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!brandForm.brandName || !brandForm.brandCode) {
    alert('请填写必填项')
    return
  }

  submitting.value = true
  try {
    const data = {
      brandName: brandForm.brandName,
      brandCode: brandForm.brandCode,
      description: brandForm.description,
      status: parseInt(brandForm.status)
    }

    let response
    if (showEditModal.value) {
      response = await updateBrand(brandForm.id, data)
    } else {
      response = await createBrand(data)
    }

    if (response.code === 0) {
      closeModal()
      loadBrandList()
    } else {
      alert(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    alert('操作失败')
  } finally {
    submitting.value = false
  }
}

// 关闭弹窗
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  // 重置表单
  Object.assign(brandForm, {
    id: null,
    brandName: '',
    brandCode: '',
    description: '',
    status: 1
  })
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadBrandList()
})
</script>

<style scoped>
.brand-layout {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-control {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #1890ff;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-separator {
  color: #666;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 10px;
  align-items: end;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.data-table td {
  font-size: 14px;
  color: #666;
}

.brand-name {
  font-weight: 500;
  color: #333;
}

.brand-desc {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-badge.inactive {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-info {
  color: #666;
  font-size: 14px;
  margin: 0 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #40a9ff;
}

.btn-secondary {
  background: #f0f0f0;
  color: #666;
}

.btn-secondary:hover:not(:disabled) {
  background: #e6e6e6;
}

.btn-info {
  background: #13c2c2;
  color: white;
}

.btn-info:hover:not(:disabled) {
  background: #36cfc9;
}

.btn-danger {
  background: #ff4d4f;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #ff7875;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-cancel {
  background: #f0f0f0;
  color: #666;
}

.btn-confirm {
  background: #1890ff;
  color: white;
}

.icon {
  font-size: 12px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.delete-modal {
  max-width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.required {
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .search-form {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    grid-column: 1 / -1;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 10px;
  }
  
  .actions {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
